package com.finalterm.product.controller;

import com.finalterm.common.result.Result;
import com.finalterm.product.config.ProductConfigProperties;
import com.finalterm.product.service.ProductCacheService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 商品配置管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/product/config")
@RequiredArgsConstructor
public class ProductConfigController {
    
    private final ProductConfigProperties productConfig;
    private final ProductCacheService productCacheService;
    
    /**
     * 获取当前缓存时间配置
     */
    @GetMapping("/cache/time")
    public Result<Integer> getCacheTime() {
        Integer cacheTime = productCacheService.getCurrentCacheTime();
        log.info("查询商品缓存时间配置: {}秒", cacheTime);
        return Result.success("获取缓存时间配置成功", cacheTime);
    }
    
    /**
     * 获取缓存统计信息
     */
    @GetMapping("/cache/stats")
    public Result<String> getCacheStats() {
        String stats = productCacheService.getCacheStats();
        log.info("查询缓存统计信息: {}", stats);
        return Result.success("获取缓存统计成功", stats);
    }
    
    /**
     * 清理过期缓存
     */
    @PostMapping("/cache/clean")
    public Result<String> cleanExpiredCache() {
        int beforeSize = productCacheService.getDetailCacheSize();
        productCacheService.cleanExpiredCache();
        int afterSize = productCacheService.getDetailCacheSize();
        
        String message = String.format("缓存清理完成，清理前: %d, 清理后: %d, 清理数量: %d", 
                beforeSize, afterSize, beforeSize - afterSize);
        
        log.info(message);
        return Result.success(message);
    }
    
    /**
     * 测试缓存功能
     */
    @PostMapping("/cache/test/{productId}")
    public Result<String> testCache(@PathVariable Long productId) {
        // 先检查缓存
        boolean hasCached = productCacheService.getCachedProductDetail(productId) != null;
        
        String message = String.format("商品ID: %d, 缓存状态: %s, 当前缓存时间配置: %d秒", 
                productId, 
                hasCached ? "已缓存" : "未缓存", 
                productCacheService.getCurrentCacheTime());
        
        log.info("缓存测试: {}", message);
        return Result.success(message);
    }
    
    /**
     * 获取商品配置详情
     */
    @GetMapping("/details")
    public Result<ProductConfigProperties> getProductConfig() {
        log.info("查询商品配置详情");
        return Result.success("获取商品配置成功", productConfig);
    }
}
